package br.usp.wta.validator;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import br.usp.language.automata.StateMachine;
import br.usp.language.morph.AnalisadorMorfologico;
import br.usp.language.morph.MorphologicAnalyser;

public class JJValidator implements GrammarValidator {
    
    private static final String DICFILE = "resources/port";
    private static final String LISTFILE = "resources/port_amor_config.list";

    private StateMachine stateMachine;
    private List<String> positiveStataments, negativeStatements;

    private MorphologicAnalyser morphologicAnalyser;
    
    private double correctAcceptions, correctRejections, wrongAcceptions, wrongRejections;
    
    public JJValidator(StateMachine stateMachine) throws IOException {

        this.positiveStataments = StatementsProvider.getPositiveStatements();
        this.negativeStatements = StatementsProvider.getNegativeStatements();
        
        morphologicAnalyser = new AnalisadorMorfologico(DICFILE);
        this.stateMachine = stateMachine;
    }

    public void verify() {
        
        for (String sentence: this.positiveStataments) {
            if (this.verifySentence(sentence))
                this.correctAcceptions++;
            else
                this.wrongAcceptions++;
        }

        for (String sentence: this.negativeStatements) {
            if (!this.verifySentence(sentence))
                this.correctRejections++;
            else
                this.wrongRejections++;
        }

    }
    
    private boolean verifySentence(String sentence) {
        
        StringReader reader = new StringReader(sentence);
        this.morphologicAnalyser.setInput(reader);
        this.stateMachine.restart();
        
        while (this.morphologicAnalyser.hasMoreTokens()) {
            String cat = this.morphologicAnalyser.getNextToken().getType();
            this.stateMachine.input(cat);
        }
        try {
            this.finalize();
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return this.stateMachine.isAtAcceptState();
    }
    
    public double getCorrectAcceptionRate() {
        
        return this.correctAcceptions / (this.correctAcceptions + this.wrongAcceptions);
    }

    public double getCorrectRejectionRate() {
        
        return this.correctRejections / (this.correctRejections + this.wrongRejections);
    }
    
    public void printResult() {
        
        System.out.println("Correct accpetion rate: " + this.getCorrectAcceptionRate());
        System.out.println("Correct rejection rate: " + this.getCorrectRejectionRate());
    }

}
